package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.StackLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.ResourceResponse;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.system.version.SystemVersion;
import ohos.utils.net.Uri;

import java.io.*;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public class SdkListSlice extends AbilitySlice
{
    DirectionalLayout Slice_webview = null;
    StackLayout layout_webview = null;
    WebView webView = null;
    Component cover = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_privacy_statement);
        //设定状态栏沉浸
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xFEEFF4)));
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        Slice_webview = (DirectionalLayout) findComponentById(ResourceTable.Id_Slice_webview);
        webView = new WebView(this);
        webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        webView.setVisibility(Component.INVISIBLE);
        Slice_webview.addComponent(webView);
        layout_webview = (StackLayout)findComponentById(ResourceTable.Id_Layout_webview);
        cover= new Component(this);
        cover.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        cover.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        cover.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_bg, Color.getIntColor("#F7EDD8"))));}});
        cover.setVisibility(Component.VISIBLE);
        cover.setClickedListener(c->{try{webView.setVisibility(Component.VISIBLE);}catch(Exception e){}});
        layout_webview.addComponent(cover);
        webView.setWebAgent(new WebAgent()
        {
            @Override
            public void onPageLoaded(WebView webview, String url)
            {
                super.onPageLoaded(webview, url);
                try{webView.setVisibility(Component.VISIBLE);}catch(Exception e){}
            }

            @Override
            public ResourceResponse processResourceRequest(WebView webview, ResourceRequest request)
            {
                final String authority = "dawnlighti.com";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority()))
                {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path))
                    {
                        return super.processResourceRequest(webview, request);
                    }
                    String rawFilePath = "entry/resources/rawfile" + path;
                    String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                    try
                    {
                        Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                        byte[] buffer = new byte[resource.available()];
                        resource.read(buffer);
                        String htmlText = new String(buffer);
                        htmlText = htmlText.replaceFirst("dawnlighti_style",(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?"background-color:black;":"background-color:#F7EDD8;");
                        htmlText = htmlText.replaceAll("dawnlighti_text",(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?"230":"26");
                        htmlText = htmlText.replaceAll("dawnlighti_accent",(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?"#BA791B":"#F9A01E");
                        FileOutputStream out = null;
                        try
                        {
                            out = new FileOutputStream(getFilesDir()+"/temp");
                            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                            writer.write(htmlText);
                            writer.close();
                            out.flush();
                            out.close();
                        }catch(IOException ex){ex.printStackTrace();}
                        finally {try {if (out != null) out.close();} catch(IOException e){}}
                        try {
                            InputStream inputStream = new FileInputStream(getFilesDir()+"/temp");
                            ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                            return response;
                        } catch (Exception e) {}
                    } catch (Exception e){}
                }
                return super.processResourceRequest(webview, request);
            }
        });
        webView.getWebConfig().setJavaScriptPermit(true);
        webView.addJsCallback("JsCallbackToApp",msg -> {openUrlInBrowser(Uri.parse(msg));return "jsResult";});
        webView.load("https://dawnlighti.com/SdkList_"+ResourceTool.getString(this,ResourceTable.String_language,"zh_CN")+".html");
        Component Actionbar_Back_Item_Pressed = findComponentById(ResourceTable.Id_actionBar_Back_Pressed_Item);
        Component Actionbar_Back_Button = findComponentById(ResourceTable.Id_actionBar_Back);
        Actionbar_Back_Button.setClickedListener(c->onBackPressed());
        Actionbar_Back_Button.setComponentStateChangedListener((c,i) ->
        {
            if(i == 18432)
                Actionbar_Back_Item_Pressed.setVisibility(Component.VISIBLE);
            else
                Actionbar_Back_Item_Pressed.setVisibility(Component.INVISIBLE);
        });
        System.gc();
    }

    private void openUrlInBrowser(Uri requestUri)
    {
        if(SystemVersion.getApiVersion() >= 6)
        {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withAction("ability.intent.VIEW_DATA")
                    .withUri(requestUri)
                    .build();
            intent.setOperation(operation);
            startAbility(intent);
        }else
        {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withAction("android.intent.action.VIEW")
                    .withUri(requestUri)
                    .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                    .build();
            intent.setOperation(operation);
            startAbility(intent);
        }
    }

    @Override
    public void onBackPressed()
    {
        DatabaseManager.Init(this);
        DatabaseManager.setString("AboutSlice_LastSceneName","None");
        try{layout_webview.removeComponent(cover);}catch(Exception e){}
        try{cover.release();}catch(Exception e){}
        try{Slice_webview.removeComponent(webView);}catch(Exception e){}
        try{webView.release();}catch(Exception e){}
        try{Slice_webview.release();}catch(Exception e){}
        try{layout_webview.release();}catch(Exception e){}
        cover = null;
        webView = null;
        Slice_webview = null;
        layout_webview = null;
        System.gc();
        super.onBackPressed();
    }

    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}